const BaseHandler = require('../base-handler');
const SystemServices = require('../../../constants').SystemServices;
const HTTP_VERBS = require('../../../constants').HTTP_VERBS;

class TasksOperationHandler extends BaseHandler {
    get pattern() {
        return "/tasks/operation/:type";
    }
    
    doGET(request, response) {
        
    }

    doPOST(request, response) {
        if (!request.session.user.authenticated) {
            response.json({
                success: false,
                error: '请登录系统后再调用此接口！'
            });
        } else {
            var type = request.params.type, bodyData = request.body,
                params = {
                    userId: request.session.user.id,
                    type,
                    data: {}
                };
            if (type == 'delete' || type == 'assign') {
                // 删除或者是标记任务完成
                params.data.wfTaskId = bodyData.wfTaskId;
                params.data.taskStatus = bodyData.taskStatus;
            } else {
                params.data = {
                    wfTaskId: bodyData.wfTaskId,
                    wfTaskName: bodyData.wfTaskName,
                    taskType: bodyData.taskType ? bodyData.taskType.id : '',
                    remindTime: bodyData.remindTime,
                    endTime: bodyData.endTime
                }
                if(bodyData.taskType) {
                    params.data.taskType = bodyData.taskType ? bodyData.taskType.id : '';
                }
                if(bodyData.customer) {
                    params.data.customerId = bodyData.customer.customerId;
                    params.data.customerName = bodyData.customer.customerName;
                }
                if(bodyData.targetUser) {
                    params.data.targetUser = bodyData.targetUser.employeId;
                    params.data.targetUserName = bodyData.targetUser.employeName;
                }
                if(bodyData.taskGroup) {
                    params.data.taskGroup = bodyData.taskGroup.wf_taskgroup_id;
                    params.data.taskGroupName = bodyData.taskGroup.wf_taskgroup_name;
                }
                if(bodyData.deal) {
                    params.data.billNo = bodyData.deal.billNo;
                }
            }
            
            this.Controller.operateTask(params, (result) => {
                if (result.error) {
                    return response.json({
                        success: false,
                        error: result.error
                    });
                }
                response.json({
                    success: true,
                    result: result
                });
            })
        }
    }

    setup() {
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
        this.registerVerb(HTTP_VERBS.POST, this.doPOST)
    }
}

module.exports = TasksOperationHandler;